package com.dbcs.persistencia;

import java.sql.Connection;
import java.util.Properties;

import com.dbcs.utilidades.LeerPropiedades;

import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

public class ConnectionPool {

	static Logger logger = Logger.getLogger("ConnectionPool.class");
	
	Properties propiedades = new LeerPropiedades().getProperties();
    
    private String URL = propiedades.getProperty("URL");
    private int Puerto = Integer.parseInt(propiedades.getProperty("PUERTO"));
    private String USR = propiedades.getProperty("USR");
    private String PASS = propiedades.getProperty("PASS");
    private String SCHEMA = propiedades.getProperty("SCHEMA");
	
    
	private static ConnectionPool connectionPool= null;
	
	private Connection connection = null;
    
	private ConnectionPool() throws SQLException{
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		this.connection = DriverManager.getConnection("jdbc:mysql://"+this.URL+":"+this.Puerto+"/"+this.SCHEMA+"?autoReconnect=true", this.USR,this.PASS);
	}
	
	public static ConnectionPool getInstance()  {
			
			try {
				if (connectionPool == null){
					connectionPool = new ConnectionPool();
				}
			} catch (SQLException e) {
				logger.error("Excepcion SQL: "+e);
			}
		
			return connectionPool;
	}
	
	
	public Connection getConnection() {
		
		try{
			if (!this.connection.isClosed() || this.connection.isValid(10)){
				
			}else{
				connectionPool = new ConnectionPool();
				
			}
		}catch(SQLException e){
			logger.error("Excepcion SQL: "+e);
		}
		
		
		return this.connection;
	}
	
	public void freeConnection() {
		try {
			this.connection.close();
		} catch (SQLException e) {
			logger.error("Excepcion SQL: "+e);
		}
	}

	
	public String getURL() {
		return this.URL;
	}

	
	public String getUsr() {
		return this.USR;
	}

	
	public int getPuerto() {
		return this.Puerto;
	}

	
	public String getPassword() {
		return this.PASS;
	}
	
}
